import 'dart:io';

import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';

import 'oss_util.dart';

class UploadImageUtils {

  static UploadImageUtils _instance;

  UploadImageUtils._();

  factory UploadImageUtils() {
    _instance ??= UploadImageUtils._();
    return _instance;
  }


  ///上传图片 file形似 多图
  void uploadMultiImages(List<File> files, HttpSuccessCallback callback) {
    List<ImagesBean> resultPaths = [];

    List<Future<String>> uploadQueue = new List();
    files.forEach((element) {
      uploadQueue.add(uploadSingleImage(element));
    });
    Future.wait(uploadQueue)
        .then((results) {
          for (int i = 0; i < results.length; i++) {
            resultPaths.add(ImagesBean(
                data: results[i],
                no: i,
                dataType: EnumUtils.enumToString(DataType.IMAGE),
                officialFlag: EnumUtils.enumToString(OfficialFlag.NO)));
          }
          if (null != callback) {
            callback.call(resultPaths);
          }
        })
        .catchError((e) {
          callback.call(resultPaths);
          print(e);
        })
        .whenComplete(() {})
        .asStream();
  }

  Future<String> uploadSingleImage(File file) async {
    String path = await OssHelper.getOssConfiguration().then((result) {
      Map<String, dynamic> ossMsg = {
        "accessKeyId": result.data['data']['accessKeyId'],
        "accessKeySecret": result.data['data']['accessKeySecret'],
        "expiration": result.data['data']['expiration'],
        "securityToken": result.data['data']['securityToken']
      };
      return ossMsg;
    }).then((oss) => singleUploadImageWithConfig(file, oss));
    return path;
  }

  Future<String> singleUploadImageWithConfig(
      File file, Map<String, dynamic> ossMsg) async {
    String path = await OssHelper.uploadToOss(file, ossMsg);
    return path;
  }
}
